package com.pirestupppai.widgets.dialog;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;

import com.orhanobut.logger.Logger;
import com.pirestupppai.R;
import com.pirestupppai.base.BaseDialog;
import com.pirestupppai.bean.FeedItem;
import com.pirestupppai.bean.LoginUser;
import com.pirestupppai.bean.ShareItem;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.rxbus.RxBus;
import com.pirestupppai.utils.DownloadUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.utils.WeakReferenceHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import rx.Subscription;
import rx.functions.Action1;

import static com.pirestupppai.rxbus.RxBus.RXBUS_DOWNLOAD_RESULT;
import static com.pirestupppai.rxbus.RxBus.RXBUS_REFRESH_FEED_LIST;

/**
 * 动态更多操作对话框
 *
 * @author: xiaoluo
 * @date: 2017-04-13 17:53
 */
public class FeedMoreDialog extends BaseDialog implements View.OnClickListener, Handler.Callback {

    private static final int MSG_DOWNLOAD_SUCCESS = 10;
    private static final int MSG_DOWNLOAD_FAILED = 20;
    private static final int MSG_SHARE_SUCCEED = 30;
    private static final int MSG_SHARE_FAILED = 40;
    private static final int MSG_SHARE_CANCELED = 50;
    private static final int MSG_GET_SHARE_DATA = 60;

    @BindView(R.id.weibo_layout)
    LinearLayout weiboLayout;
    @BindView(R.id.qq_layout)
    LinearLayout qqLayout;
    @BindView(R.id.moment_layout)
    LinearLayout momentLayout;
    @BindView(R.id.wechat_layout)
    LinearLayout wechatLayout;
    @BindView(R.id.download_my_layout)
    LinearLayout downloadMyLayout;
    @BindView(R.id.download_guest_layout)
    LinearLayout downloadGuestLayout;
    @BindView(R.id.delete_layout)
    LinearLayout deleteLayout;
    @BindView(R.id.report_layout)
    LinearLayout reportLayout;
    @BindView(R.id.collect_layout)
    LinearLayout collectLayout;

    private FeedItem mFeedItem;
    private String mTitle;
    private String mContent;
    private String mUrl;
    private String mPictureUrl;
    private List<String> mImageList = new ArrayList<>();

    private Subscription mSubscription;

    private WeakReferenceHandler mHandler = new WeakReferenceHandler(this);
    private ProgressingDialog mDialog;
    private int mCount = 0;
    private String mPlatform;

    public FeedMoreDialog(Context context, FeedItem feedItem) {
        super(context, R.style.CustomDialogStyle);
        mFeedItem = feedItem;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.dialog_feed_more;
    }

    @Override
    protected boolean atBottom() {
        return true;
    }

    protected void initViews() {
        weiboLayout = (LinearLayout) findViewById(R.id.weibo_layout);
        momentLayout = (LinearLayout) findViewById(R.id.moment_layout);
        wechatLayout = (LinearLayout) findViewById(R.id.wechat_layout);
        qqLayout = (LinearLayout) findViewById(R.id.qq_layout);
        downloadMyLayout = (LinearLayout) findViewById(R.id.download_my_layout);
        downloadGuestLayout = (LinearLayout) findViewById(R.id.download_guest_layout);
        reportLayout = (LinearLayout) findViewById(R.id.report_layout);
        collectLayout = (LinearLayout) findViewById(R.id.collect_layout);
        deleteLayout = (LinearLayout) findViewById(R.id.delete_layout);

        if (mFeedItem.getUid() == LoginUser.getInstance().getId()) {
            collectLayout.setVisibility(View.GONE);
            reportLayout.setVisibility(View.GONE);
            downloadGuestLayout.setVisibility(View.GONE);
            deleteLayout.setVisibility(View.GONE);
            if (mFeedItem.getType() == FeedItem.ASK_PS_POST) {
                downloadMyLayout.setVisibility(View.VISIBLE);
            } else {
                downloadMyLayout.setVisibility(View.GONE);
            }
        } else {
            collectLayout.setVisibility(View.GONE);
            reportLayout.setVisibility(View.VISIBLE);
            downloadMyLayout.setVisibility(View.GONE);
            deleteLayout.setVisibility(View.GONE);
            if (mFeedItem.getType() == FeedItem.ASK_PS_POST) {
                downloadGuestLayout.setVisibility(View.VISIBLE);
            } else {
                downloadGuestLayout.setVisibility(View.GONE);
            }
        }

        if (mFeedItem.getMedias() != null && mFeedItem.getMedias().size() != 0) {
            mPictureUrl = mFeedItem.getMedias().get(0).getPathname();
            for (int i = 0; i < mFeedItem.getMedias().size(); i++) {
                mImageList.add(mFeedItem.getMedias().get(i).getPathname());
            }
        }

        mDialog = new ProgressingDialog(mContext);
    }

    protected void initListeners() {
        weiboLayout.setOnClickListener(this);
        momentLayout.setOnClickListener(this);
        wechatLayout.setOnClickListener(this);
        qqLayout.setOnClickListener(this);
        downloadMyLayout.setOnClickListener(this);
        downloadGuestLayout.setOnClickListener(this);
        reportLayout.setOnClickListener(this);
        collectLayout.setOnClickListener(this);
        deleteLayout.setOnClickListener(this);

        //注册观察者
        mSubscription = RxBus.getInstance()
                .toObservable(RXBUS_DOWNLOAD_RESULT, String.class)
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mCount++;
                        if (mCount == mImageList.size()) {
                            mCount = 0;
                            downloadGuestLayout.setClickable(true);
                            downloadMyLayout.setClickable(true);
                            if (mDialog != null && mDialog.isShowing()) {
                                mDialog.dismiss();
                            }
                            dismiss();
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.weibo_layout:
                getShareData(SinaWeibo.NAME);
                break;
            case R.id.moment_layout:
                getShareData(WechatMoments.NAME);
                break;
            case R.id.wechat_layout:
                getShareData(Wechat.NAME);
                break;
            case R.id.qq_layout:
                getShareData(QQ.NAME);
                break;
            case R.id.download_my_layout:
                downloadRequest();
                break;
            case R.id.download_guest_layout:
                downloadRequest();
                break;
            case R.id.report_layout:
                dismiss();
                ReportDialog dialog = new ReportDialog(mContext, mFeedItem);
                dialog.show();
                break;
            case R.id.collect_layout:
                collectLayout.setClickable(false);
                break;
            case R.id.delete_layout:
                deleteFeed();
                break;
        }
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (!mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
        }
    }

    /**
     * 下载请求
     */
    private void downloadRequest() {
        if (mImageList.size() == 0) {
            return;
        }
        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
        }
        downloadGuestLayout.setClickable(false);
        downloadMyLayout.setClickable(false);

        DownloadUtil.downloadImage(mImageList);
    }


    /**
     * 删除动态
     */
    private void deleteFeed() {
        NetworkRequest.getInstance().deleteFeed(mFeedItem.getId(), mContext,
                new TupaiSubscriber<FeedItem>(mContext) {
                    @Override
                    protected void requestSuccess(FeedItem item) {
                        Utils.showToast("删除成功");
                        RxBus.getInstance().post(RXBUS_REFRESH_FEED_LIST, "");
                        dismiss();
                    }

                    @Override
                    protected void requestError(String error) {

                    }
                });
    }

    /**
     * 分享操作
     */
    private void share(String name) {
        Platform platform = ShareSDK.getPlatform(name);
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                mHandler.sendEmptyMessage(MSG_SHARE_SUCCEED);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Logger.d("onError:" + throwable.toString());
                mHandler.sendEmptyMessage(MSG_SHARE_FAILED);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                mHandler.sendEmptyMessage(MSG_SHARE_CANCELED);
            }
        });

        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setShareType(Platform.SHARE_WEBPAGE);  // 设置图文分享
        if (name.equals(SinaWeibo.NAME)) {
            mContent += " " + mUrl;
            sp.setText(mContent);
            sp.setImageUrl(mPictureUrl);
        } else if (name.equals(QQ.NAME)) {
            sp.setText(mContent);
            sp.setTitle(mTitle);
            sp.setImageUrl(mPictureUrl);
            sp.setImagePath(mPictureUrl);
            sp.setTitleUrl(mUrl);
        } else {
            sp.setText(mContent);
            sp.setTitle(mTitle);
            sp.setImageUrl(mPictureUrl);
            sp.setUrl(mUrl);
        }
        platform.share(sp);
    }

    /**
     * 获取分享数据
     */
    private void getShareData(String name) {
        mPlatform = name;
        if (mDialog != null && !mDialog.isShowing()) {
            mDialog.show();
        }
        NetworkRequest.getInstance().getShareData(mFeedItem.getId(), mContext,
                new TupaiSubscriber<ShareItem>(mContext) {
                    @Override
                    protected void requestSuccess(ShareItem item) {
                        mTitle = item.getTitle();
                        mContent = item.getDesc();
                        mUrl = item.getUrl();
                        mHandler.sendEmptyMessage(MSG_GET_SHARE_DATA);
                    }

                    @Override
                    protected void requestError(String error) {
                        if (mDialog != null && mDialog.isShowing()) {
                            mDialog.dismiss();
                        }
                    }
                });
    }

    /**
     * 设置分享标题,没有可不设或设为空
     */
    public FeedMoreDialog setTitle(String title) {
        this.mTitle = title;
        return this;
    }

    /**
     * 设置分享内容,没有可不设或设为空
     */
    public FeedMoreDialog setContent(String content) {
        this.mContent = content;
        return this;
    }

    /**
     * 设置分享链接,没有可不设或设为空
     */
    public FeedMoreDialog setUrl(String url) {
        this.mUrl = url;
        return this;
    }

    /**
     * 设置分享图片地址,没有可不设或设为空
     */
    public FeedMoreDialog setPictureUrl(String picUrl) {
        this.mPictureUrl = picUrl;
        return this;
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_DOWNLOAD_SUCCESS:
                Utils.showToast("下载成功!");
                break;
            case MSG_DOWNLOAD_FAILED:
                Utils.showToast("下载失败~");
                break;
            case MSG_SHARE_CANCELED:
                Utils.showToast("取消分享");
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                break;
            case MSG_SHARE_SUCCEED:
                Utils.showToast("分享成功");
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                break;
            case MSG_SHARE_FAILED:
                Utils.showToast("分享失败");
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                break;
            case MSG_GET_SHARE_DATA:
                share(mPlatform);
                break;
        }
        dismiss();
        return true;
    }
}
